package com.cskaoyan.controller.wx;

import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.Storage;
import com.cskaoyan.service.wx.WxStorageService;
import com.cskaoyan.util.StorageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;

/**
 * @author pengyehua
 * @date 2020/12/8 15:05
 */
@RestController
public class WxStorageController {

    @Value("${file.path}")
    String filePath;

    @Value("${server.port}")
    String port;

    @Autowired
    WxStorageService wxStorageService;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("wx/storage/upload")
    public BaseRespVo upload(MultipartFile file) throws ClassNotFoundException, UnknownHostException {
        Storage storage = StorageUtils.setStorageInfo(file);

        //获取classpath路径
        URL resource = Class.forName("com.cskaoyan.controller.wx.WxStorageController").
                getClassLoader().
                getResource("");
        System.out.println(resource);
        String path = resource.getPath();
        File picFile = new File(path + filePath, storage.getKey());
        //将文件保存到服务器
        try {
            file.transferTo(picFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String hostAddress = InetAddress.getLocalHost().getHostAddress();
        storage.setUrl("http://" + hostAddress + ":" + port + "/upload/" + storage.getKey());
        Storage storageVo = wxStorageService.upload(storage);
        return BaseRespVo.ok(storageVo);
    }
}
